package com.kaibes.web.permission;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import com.kaibes.core.base.util.IntegerUtils;
import com.kaibes.web.filter.BasicInterceptor;

@Component
public class PermissionInterceptor implements BasicInterceptor {

    @Autowired(required = false)
    private PermissionChecker permissionChecker;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            if (handlerMethod.getBeanType().getName().startsWith("org.springframework")) {
                return true;
            }

            if (permissionChecker == null) {
                // 不需要权限也就不需要登陆
                return true;
            }
            
            Integer userId = (Integer) request.getAttribute("userId");
            if (permissionChecker.hasPermission(userId, request.getRequestURI(), request.getMethod())) {
                return true;
            }

            if (IntegerUtils.isZero(userId)) {
                // 需要权限但是没有登陆
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
                // 登陆了却没有权限
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            }
            return false;
        }
        return true;
    }

}
